<template>
    <el-affix :offset="0">
        <el-menu ref="menu" :default-active="activeIndex" mode="horizontal" :ellipsis="false" router @select="selectMenu">
            <el-menu-item index="/home">
                <template #title>
                    <el-text type="primary" size="large">
                        <h1 class="my-h1">蛋糕商城</h1>
                    </el-text>
                </template>
            </el-menu-item>
            <el-sub-menu index="/goods">
                <template #title>
                    <el-icon>
                        <Goods />
                    </el-icon>
                    <span>商品分类</span>
                </template>
                <el-menu-item index="/goods">全部商品</el-menu-item>
                <div v-for="(type, index) in typeList" :key="index">
                    <el-menu-item :index="getTidPath(type)">{{ type.name }}</el-menu-item>
                </div>
            </el-sub-menu>
            <el-menu-item index="/recommend">
                <el-icon>
                    <Star />
                </el-icon>
                <span>热销推荐</span>
            </el-menu-item>
            <el-menu-item index="/cart">
                <template #title>
                    <el-icon size="40px">
                        <ShoppingCart />
                    </el-icon>
                    <span>购物车</span>
                </template>
            </el-menu-item>
            <el-menu-item index="/my_orders">
                <template #title>
                    <el-icon size="40px">
                        <Tickets />
                    </el-icon>
                    <span>我的订单</span>
                </template>
            </el-menu-item>
            <el-menu-item v-if="this.$store.state.user.isAdmin && !this.$store.state.onAdmin" @click="showAdminAside">
                <template #title>
                    <el-icon size="40px">
                        <Setting />
                    </el-icon>
                    <span>显示管理侧边栏 &gt;&gt;&gt;</span>
                </template>
            </el-menu-item>
            <div style="flex-grow: 1;" />
            <el-input ref="searchInput" v-model="searchVal" placeholder="请输入关键字" @keydown="keyEntry" class="my-search"
                clearable>
                <template #suffix>
                    <el-button @click="search" type="primary" text circle>
                        <el-icon size="15px">
                            <Search />
                        </el-icon>
                    </el-button>
                </template>
            </el-input>
            <el-menu-item index="/oneself" v-if="$store.state.isLogin">
                <template #title>
                    <el-avatar>{{ $store.state.user.username }}</el-avatar>
                </template>
            </el-menu-item>
            <el-menu-item index="/login" v-if="!$store.state.isLogin">登录</el-menu-item>
            <el-menu-item index="/register" v-if="!$store.state.isLogin">注册</el-menu-item>
        </el-menu>
    </el-affix>
    <el-backtop :visibility-height="50" :right="40" :bottom="40" />
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';
import router from '@/router';

axios.defaults.baseURL = '/api';

export default {
    data() {
        return {
            activeIndex: '',
            searchVal: '',
            typeList: [],
        }
    },
    //在组件挂载前
    beforeMount() {
        //触发自动登录
        this.$store.state.isLogin = true;
    },
    mounted() {
        var url = new URL(window.location.href);

        this.activeIndex = url.pathname;

        if (url.pathname === '/') {
            this.activeIndex = '/home';
        }

        //同步导航状态
        this.$store.state.navActive = this.activeIndex;

        axios.get("/type")
            .then(result => {
                if (result.data.code === 1) {
                    this.typeList = result.data.data;
                }
            })
            .catch(err => {
                console.log(err);
                if (err.response.status === 500) {
                    ElMessage.error("无法连接后端服务器");
                }
            })
    },
    methods: {
        routerTo(path) {
            router.push(path);
        },
        search() {
            if (this.searchVal === '') {
                ElMessage.info("请填写搜索关键字！！！");
                return;
            }
            // ElMessage.info("搜索：" + this.searchVal);
            this.$store.state.navActive = '/search?value=' + this.searchVal;
        },
        selectMenu(index) {
            if (index !== this.activeIndex) {
                this.activeIndex = index;
                this.routerTo(index);
                //同步导航状态
                if (this.$store.state.navActive !== this.activeIndex) {
                    this.$store.state.navActive = this.activeIndex;
                }
            }
        },
        verify() {
            //自动登录标志异常
            if (!this.$store.state.isLogin) {
                this.$store.state.isLogin = true;
                return;
            }
            let token = this.$cookies.get('token');
            console.log("token: " + token);

            if (token !== null) {
                axios.get("/login/" + token)
                    .then(result => {
                        //token获取用户信息
                        if (result.data.code === 1) {
                            this.$store.state.user = result.data.data;
                            localStorage.setItem('store', JSON.stringify(this.$store.state));
                            ElMessage.success(this.$store.state.user.username + " 登录成功");
                        } else if (result.data.msg === "Invalid_token") {
                            //无效token
                            console.log("无效token");
                            ElMessage.info("自动登录过期");
                            this.$cookies.remove('token');
                            this.$store.state.isLogin = false;
                        }
                    })
                    .catch(err => {
                        console.log(err);
                        if (err.response.status === 500) {
                            this.$store.state.isLogin = false;
                            ElMessage.error("无法连接后端服务器");
                            return;
                        }
                        this.$store.state.isLogin = false;
                        console.log("异常：" + err);
                        ElMessage.error("异常：" + err);
                    })
            } else {
                this.$store.state.isLogin = false;
            }
        },
        keyEntry(event) {
            if (event.keyCode === 13) {
                this.search();
            }
        },
        getTidPath(type) {
            return "/goods?type=" + type.tid;
        },
        showAdminAside() {
            this.$store.state.onAdmin = true;
        }
    },
    watch: {
        '$store.state.isLogin'() {
            if (this.$store.state.isLogin) {
                this.verify();
            } else {
                this.$store.state.user = {};
            }
        },
        '$store.state.navActive'() {
            console.log("this.$store.state.navActive: " + this.$store.state.navActive);
            this.selectMenu(this.$store.state.navActive);
        }
    }
}
</script>

<style scoped>
.my-h1 {
    color: #000;
    text-align: center;
    font-size: 28px;
}

.my-search {
    width: 15% !important;
    height: 60% !important;
    margin-top: 15px !important;
    margin-right: 15px !important;
    transition: all 0.25s ease-in-out;
}

.my-search:focus-within {
    width: 30% !important;
    height: 80% !important;
    margin-top: 8px !important;
}</style>